//
//  UpdateView.m
//  MQBrowser
//
//  Created by 巩小鹏 on 2016/12/22.
//  Copyright © 2016年 巩小鹏. All rights reserved.
//
#define KSFullScreen [UIScreen mainScreen].bounds

#define __kScreenHeight__ [[UIScreen mainScreen] bounds].size.height
#define __kScreenWidth__ [[UIScreen mainScreen] bounds].size.width

#import "UpdateView.h"
#import "UpdateAppearance.h"
#import "Masonry.h"
#import <objc/runtime.h>

@interface UpdateView ()
{
    NSTimeInterval _druation;
    CGFloat  _alertGsViewHeight;
    CGFloat  _bodyHeight;
}
@property (nonatomic, strong) UIWindow* window;
@property (nonatomic, strong) UIView* alertGsView;
@property (nonatomic, strong) UIView* selectGsView;
@property (nonatomic, strong) UIView* centerXian;
@property (nonatomic, strong) UIView * bottomXian;

@end

@implementation UpdateView


- (void)show{
    
    [self.window makeKeyWindow];
    [self.window makeKeyAndVisible];
   
    [self setShowUpdateAnimation];
}
- (void)dismisss{
    
    [self.window resignKeyWindow];
    
//    [[UIApplication sharedApplication].delegate.window makeKeyAndVisible];
//
//    [[UIApplication sharedApplication].delegate.window becomeKeyWindow];
    
    [self removeFromSuperview];
}

-(void)updateClick:(UIButton *)btn{
    if (btn.selected) {
        [btn setImage:[UIImage imageNamed:@"remind_bird_1"] forState:UIControlStateNormal];
         btn.selected = NO;
    }else{
        [btn setImage:[UIImage imageNamed:@"remind_bird_2"] forState:UIControlStateNormal];
        btn.selected = YES;
    }
}

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message maqueVersion:(NSString *)maqueVersion cancelButton:(NSString*)cancelTitle commitButton:(NSString*)commitTitle cancelAction:(CancelAction)cancelAction commitAction:(CommitAction)commitAction druation:(NSTimeInterval)druation{
    
    if (self = [super init]) {
//===========================================================================================================
        {
            
            //初始化窗体
//            self.window = [[UIWindow alloc] initWithFrame:KSFullScreen];
             self.window.windowLevel = UIWindowLevelAlert;
             [self.window addSubview:self];
        }
//===========================================================================================================
        {
            [self u_background];
        }
//===========================================================================================================
        
        {
            [self addSubview:self.alertGsView];

        }
//===========================================================================================================
        {
             if (title) {
            [_alertGsView addSubview:self.titleUpdateLable];
            _titleUpdateLable.text = title;

             }
        }
//===========================================================================================================
        {
            if (message) {
                
                [_alertGsView addSubview:self.bodyContentView];
                NSString * strVer = [NSString stringWithFormat:@"发现新版本 %@",maqueVersion];
                [self p_createWeb:message title:strVer];

            }
        }
//===========================================================================================================
        {
            [_alertGsView addSubview:self.selectGsView];
            [_selectGsView addSubview:self.selectUpdateBtn];
            [_selectGsView addSubview:self.selectUpdateLable];

            _selectUpdateLable.text = @"不再提醒该版本更新";
            [_selectUpdateBtn addTarget:self action:@selector(updateClick:) forControlEvents:UIControlEventTouchUpInside];
        }
//===========================================================================================================
        {
            
            if (cancelTitle) {
                 [_alertGsView addSubview:self.cancelUpdateBtn];
                [_cancelUpdateBtn setTitle:cancelTitle forState:UIControlStateNormal];
                [_cancelUpdateBtn cancelControlEvent:UIControlEventTouchUpInside withBlock:cancelAction];
                [_cancelUpdateBtn addTarget:self action:@selector(dismisss) forControlEvents:UIControlEventTouchUpInside];
            }
           

        }
//===========================================================================================================
        {
           
            if (commitTitle) {
                
                 [_alertGsView addSubview:self.commitUpdateBtn];
                [_commitUpdateBtn setTitle:commitTitle forState:UIControlStateNormal];
                [_commitUpdateBtn handleControlEvent:UIControlEventTouchUpInside withBlock:commitAction];
                [_commitUpdateBtn addTarget:self action:@selector(dismisss) forControlEvents:UIControlEventTouchUpInside];
            }
            

        }
//===========================================================================================================
        {
            //水平分割线
            if (cancelTitle || commitTitle) {
                [_alertGsView addSubview:self.bottomXian];
            }
            //垂直分割线
            if (commitTitle) {
                [_commitUpdateBtn addSubview:self.centerXian];
            }

        }
        
        //保存变量
        _druation = druation;
        //根据bodyStr的长度自动适配计算弹窗的高度
        [self allHeight];
    }
    return self;
}


-(void)u_addUI{
    
    [_alertGsView addSubview:self.titleUpdateLable];
    [_alertGsView addSubview:self.bodyContentView];
    [_alertGsView addSubview:self.selectUpdateBtn];
    [_alertGsView addSubview:self.selectUpdateLable];
    [_alertGsView addSubview:self.cancelUpdateBtn];
    [_alertGsView addSubview:self.commitUpdateBtn];
    [self u_background];
    
}

-(void)allHeight{
    
    _alertGsViewHeight = _bodyHeight + 40 + 50 + 40;
    
//    if (_alertGsViewHeight >= (__kScreenHeight__-100)) {
//        _alertGsViewHeight = __kScreenHeight__-100;
//    }
}

- (void)layoutSubviews{
    
    [_alertGsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.left.right.mas_equalTo(self).insets(UIEdgeInsetsMake(0, 40, 0, 40));
        make.height.mas_equalTo(_alertGsViewHeight);
    }];
    
    [_titleUpdateLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.alertGsView.mas_top).mas_offset(10);
        make.left.right.mas_equalTo(self.alertGsView);
    }];
    [_bodyContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleUpdateLable.mas_bottom).mas_offset(0);
        make.left.right.mas_equalTo(self.alertGsView).insets(UIEdgeInsetsMake(0, 20, 0, 20));
        make.height.mas_equalTo(_bodyHeight);
    }];
    [_selectGsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.bottomXian.mas_top).mas_offset(0);
        make.left.right.mas_equalTo(self.alertGsView).insets(UIEdgeInsetsMake(0, 20, 0, 20));
        make.height.mas_equalTo(40);
    }];
    [_selectUpdateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.selectGsView);
        make.left.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake((40),(40)));
    }];
    [_selectUpdateLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.selectUpdateBtn);
        make.left.equalTo(self.selectUpdateBtn.mas_right).mas_offset(6);
//        make.size.mas_equalTo(CGSizeMake((496),(98)));
    }];
    [_cancelUpdateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.alertGsView.mas_bottom).mas_offset(0);
        make.left.mas_equalTo(self.alertGsView);
        make.size.mas_equalTo(CGSizeMake((__kScreenWidth__-80)/2,(50)));
    }];
    [_commitUpdateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.alertGsView.mas_bottom).mas_offset(0);
        make.right.mas_equalTo(self.alertGsView);
        make.size.mas_equalTo(CGSizeMake((__kScreenWidth__-80)/2,(50)));
    }];
    [_bottomXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.commitUpdateBtn.mas_top).mas_offset((0));
        make.left.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(__kScreenWidth__-80,(1)));
    }];
    [_centerXian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bottomXian.mas_top).mas_offset(0);
        make.centerX.equalTo(self.alertGsView);
        make.size.mas_equalTo(CGSizeMake((1),(100)));
    }];

    if (!_cancelUpdateBtn) {
        [self updateLayoutFrame];
    }
}

-(void)updateLayoutFrame{
    
   
    [_commitUpdateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.alertGsView.mas_bottom).mas_offset(0);
        make.centerX.mas_equalTo(self.alertGsView);
        make.size.mas_equalTo(CGSizeMake((__kScreenWidth__-80),(50)));
    }];
    
    _centerXian.alpha = 0;
    _selectGsView.alpha = 0;
}


+ (UpdateAppearance *)updateappearances{
    
    static UpdateAppearance* updateappearances = nil;
    static dispatch_once_t onceUpdateToken;
    dispatch_once(&onceUpdateToken, ^{
        updateappearances = [[UpdateAppearance alloc] init];
    });
    
    return updateappearances;
}

- (void)setShowUpdateAnimation{
    
    switch ([UpdateView updateappearances].GSAlertAnimationStyle) {
        case UpdateAlertAnimationStyleDefault:
        {
            CGPoint startPoint = CGPointMake(self.center.x, -_alertGsView.frame.size.height);
            _alertGsView.layer.position=startPoint;
            
            [UIView animateWithDuration:.8 delay:0 usingSpringWithDamping:.5 initialSpringVelocity:1.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                _alertGsView.layer.position=self.center;
                
            } completion:^(BOOL finished) {
                
                if (_druation) {
                    [UIView animateWithDuration:.25 delay:_druation options:UIViewAnimationOptionCurveEaseInOut animations:^{
                        self.alpha = 0;
                    } completion:^(BOOL finished) {
                        [self dismisss];
                    }];
                }
            }];
        }
            break;
    }
}



#pragma mark - 初始化UI



//背景区域
-(void)u_background{
    
    self.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.6];
    self.frame = KSFullScreen;
    self.userInteractionEnabled = YES;
}
//初始化窗体
- (UIWindow *)window{
     if (!_window) {
        NSEnumerator*frontToBackWindows = [UIApplication.sharedApplication.windows reverseObjectEnumerator];
        for(UIWindow*window in frontToBackWindows)
        {
            BOOL windowOnMainScreen = window.screen==UIScreen.mainScreen;
            BOOL windowIsVisible = !window.hidden&& window.alpha>0;
            BOOL windowLevelSupported = (window.windowLevel>=UIWindowLevelNormal&& window.windowLevel<=UIWindowLevelNormal);
            BOOL windowKeyWindow = window.isKeyWindow;
            if(windowOnMainScreen && windowIsVisible && windowLevelSupported && windowKeyWindow)
                {
                    _window = window;
                }
        }
        _window = [[[UIApplication sharedApplication] delegate] window];
    }
    return _window;
}


//显示区域
-(UIView *)alertGsView{
    if (!_alertGsView) {
        _alertGsView = [[UIView alloc]initWithFrame:CGRectZero];
        _alertGsView.backgroundColor = [UIColor whiteColor];
        _alertGsView.userInteractionEnabled = YES;
        _alertGsView.layer.masksToBounds = YES;
        _alertGsView.layer.cornerRadius = 4.0;
    }
    return _alertGsView;
}

-(UILabel *)titleUpdateLable{
    if (_titleUpdateLable == nil) {
        _titleUpdateLable = [[UILabel alloc]init];
        _titleUpdateLable.textColor = [UIColor blackColor];
        _titleUpdateLable.font = [UIFont systemFontOfSize:18];
        _titleUpdateLable.backgroundColor = [UIColor clearColor];
        _titleUpdateLable.textAlignment = NSTextAlignmentCenter;
//        _titleUpdateLable.layer.masksToBounds = YES;
//        _titleUpdateLable.layer.cornerRadius = 4.0;
    }
    return _titleUpdateLable;
}
-(UIWebView *)bodyContentView{
    if (_bodyContentView == nil) {
        _bodyContentView = [[UIWebView alloc]init];
        _bodyContentView.backgroundColor = [UIColor whiteColor];
//        _bodyContentView.layer.masksToBounds = YES;
//        _bodyContentView.layer.cornerRadius = 4.0;
        //取消右侧，下侧滚动条，去处上下滚动边界的黑色背景
        for (UIView *_aView in [_bodyContentView subviews])
        {
            if ([_aView isKindOfClass:[UIScrollView class]])
            {
                [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
                //右侧的滚动条
                
                [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
                //下侧的滚动条
                
                for (UIView *_inScrollview in _aView.subviews)
                {
                    if ([_inScrollview isKindOfClass:[UIImageView class]])
                    {
                        _inScrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                    }
                }
            }
        }
    }
    return _bodyContentView;
}

- (UIButton *)selectUpdateBtn{
    if (_selectUpdateBtn == nil) {
        _selectUpdateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_selectUpdateBtn setImage:[UIImage imageNamed:@"remind_bird_1"] forState:UIControlStateNormal];
//        _selectUpdateBtn.backgroundColor = [UIColor colorWithHexString:@"#84d22f"];
        
    }
    return _selectUpdateBtn;
}
-(UILabel *)selectUpdateLable{
    if (_selectUpdateLable == nil) {
        
        _selectUpdateLable = [[UILabel alloc]init];
        _selectUpdateLable.textColor = [UIColor blackColor];
        _selectUpdateLable.font = [UIFont systemFontOfSize:12];
        _selectUpdateLable.backgroundColor = [UIColor whiteColor];
        _selectUpdateLable.textAlignment = NSTextAlignmentLeft;

    }
    return _selectUpdateLable;
}

-(UIButton *)cancelUpdateBtn{
    if (!_cancelUpdateBtn) {
        _cancelUpdateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelUpdateBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_cancelUpdateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _cancelUpdateBtn.backgroundColor = [UIColor whiteColor];

    }
    return _cancelUpdateBtn;
}
-(UIButton *)commitUpdateBtn{
    if (!_commitUpdateBtn) {
        _commitUpdateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitUpdateBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_commitUpdateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        _commitUpdateBtn.backgroundColor = [UIColor whiteColor];
        
    }
    return _commitUpdateBtn;
}
-(UIView *)selectGsView{
    if (!_selectGsView) {
        _selectGsView = [[UIView alloc]init];
        _centerXian.backgroundColor = [UIColor whiteColor];

    }
    return _selectGsView;
}
-(UIView *)centerXian{
    if (!_centerXian) {
        _centerXian = [[UIView alloc]init];
        _centerXian.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    }
    return _centerXian;
}
-(UIView *)bottomXian{
    if (!_bottomXian) {
        _bottomXian = [[UIView alloc]init];
        _bottomXian.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    }
    return _bottomXian;
}

#pragma mark - 公有方法

+ (void)gsWithTitle:(NSString*)title message:(NSString*)message maqueVersion:(NSString *)maqueVersion cancelButton:(NSString*)cancelTitle customButton:(NSString*)commitTitle cancelAction:(CancelAction)cancelAction commitAction:(CommitAction)commitAction
{
    //GCD延迟
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UpdateView* alertView = [[UpdateView alloc] initWithTitle:title message:message maqueVersion:maqueVersion cancelButton:cancelTitle commitButton:commitTitle cancelAction:cancelAction commitAction:commitAction druation:0];
        
        [alertView show];
        
    });
   
}
+ (void)gsWithTitle:(NSString*)title message:(NSString*)message maqueVersion:(NSString *)maqueVersion customButton:(NSString*)commitTitle commitAction:(CommitAction)commitAction
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    UpdateView* alertView = [[UpdateView alloc] initWithTitle:title message:message maqueVersion:maqueVersion cancelButton:nil commitButton:commitTitle cancelAction:nil commitAction:commitAction druation:0];
    
    [alertView show];
    });
}

#pragma mark - 私有方法
-(void)p_createWeb:(NSString*) body title:(NSString *)title
{
    
    NSString *strOne = [NSString stringWithFormat:@"<span style=\"padding-mas_top: 6px;text-align:left;font-size:16px;display:block;line-height:36px \">%@</span>",title];
    NSString * str = [NSString stringWithFormat:@"<span style=\"font-size:14px;line-height:23px\">%@</span>",body];
    
//    NSString * bodyStr = [NSString stringWithFormat:@"<div style=\"font-size:%@px\">%@</div>",self.fontSizeStr,body];
    NSString * bodyStr = [NSString stringWithFormat:@"%@%@<p> </p>",strOne,str];
    //计算内容高度
    _bodyHeight = [self getStringHeightWithText:bodyStr font:14 viewWidth:__kScreenWidth__-80];

    [_bodyContentView loadHTMLString:bodyStr baseURL:nil];
    
}


- (CGFloat)getStringHeightWithText:(NSString *)text font:(CGFloat)font viewWidth:(CGFloat)width {
    // 设置文字属性 要和label的一致
    NSDictionary *attrs = @{NSFontAttributeName :[UIFont systemFontOfSize:font]};
    CGSize maxSize = CGSizeMake(width, MAXFLOAT);
    
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    // 计算文字占据的宽高
    CGSize size = [text boundingRectWithSize:maxSize options:options attributes:attrs context:nil].size;
    
    // 当你是把获得的高度来布局控件的View的高度的时候.size转化为ceilf(size.height)。
    return  ceilf(size.height);
}

@end


@implementation UIButton (gsblock)

static char overviewKey;
static char cancelviewKey;

@dynamic event;

- (void)handleControlEvent:(UIControlEvents)event withBlock:(CommitAction)block {
    objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}
- (void)cancelControlEvent:(UIControlEvents)event withBlock:(CancelAction)block {
    objc_setAssociatedObject(self, &cancelviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(canceActionlBlock:) forControlEvents:event];
}
- (void)handleControlEvent:(UIControlEvents)event CancelBlock:(CancelAction)cancelblock withBlock:(CommitAction)block {
    objc_setAssociatedObject(self, &overviewKey, cancelblock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &overviewKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event];
}

- (void)callActionBlock:(id)sender {
    CommitAction block = (CommitAction)objc_getAssociatedObject(self, &overviewKey);
    
    if (block) {
        __weak typeof(self) weakSelf = self;
        block(weakSelf);
    }
}
- (void)canceActionlBlock:(id)sender {
    CancelAction block = (CancelAction)objc_getAssociatedObject(self, &cancelviewKey);
    
    if (block) {
        __weak typeof(self) weakSelf = self;
        block(weakSelf);
    }
}
@end
